#include "LPC11xx.h"
#include "gpio.h"
#include "timer.h"
#include "ssp.h"
#include "sinetable.h"
#include "utilio.h"

/***************************************************************
 * Macro definitions                                           *
 ***************************************************************/
#define us2TimerInterval(us) ( us * (SystemAHBFrequency / 1000000) )
#define ms2TimerInterval(ms) ( ms * (SystemAHBFrequency / 1000) )

#define TIMER_DELAY     TIMER32[0]
#define TIMER_EVENT     TIMER16[0]

#define SPI_PORT    0


#define DAC_TIME    10
#define SAMPLE_FREQ (1000000 / DAC_TIME)

/***************************************************************
 * Globol variables                                            *
 ***************************************************************/
static uint32_t psw = 1;

static uint32_t curPos = 0;


/***************************************************************
 * Globol functions                                            *
 ***************************************************************/
extern void delayus(uint32_t us)
{
    TimerDelayUs(TIMER_DELAY, us);
}

/***************************************************************
 * Functions                                                   *
 ***************************************************************/

void dacNeedWrite(void *unuse)
{
    // no need to do this....
//    if (curPos == 0xffffffff) {
//        curPos = 0;
//    }
//    

    LPC_GPIO0->DATA &= ~(0x01 << 2);
    SSPSendByte(SPI_PORT, theSine[curPos >> 24]);
    LPC_GPIO0->DATA |= 0x01 << 2;
    
    curPos += psw;
    
    return;
}

/***************************************************************
 * MAIN                                                        *
 ***************************************************************/
int main (void)
{
    uint32_t freq = 20; // Hz
    
    SystemInit();             /* MUST BE INCLUDED! */

    GPIOInit();
    GPIOSetDir(PORT2, 7, GPIO_DIR_OUTPUT);

    // for delay
    TimerInit(TIMER_DELAY);
    // init spi.
    SSPInit(SPI_PORT, SSP_ClockPolarity_Low, SSP_ClockPhase_RisingEdge);
    
    TimerInit(TIMER_EVENT);
    TimerSetIntCallback(TIMER_EVENT, dacNeedWrite);
    TimerSetTime(TIMER_EVENT, us2TimerInterval(DAC_TIME));
    TimerEnable(TIMER_EVENT);
    
    MyStdin = KEY;
    MyStdout = LCD+ECHO;
    UtilioInit();
    
    while (1) {
        printf("freq: ");
        scanf("%d", &freq);
       // freq = 10000;
        psw = freq * (0xffffffff/SAMPLE_FREQ);
        GPIOSetValue(2, 7, !GPIOGetValue(2, 7));
//        TimerDelayMs(TIMER_DELAY, 500);
    }
}

/***************************************************************
 * END OF FILE                                                 *
 ***************************************************************/
